package be.bonamis.umpire.business.config;

import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;

@Configuration
@Profile("default")
@PropertySource("classpath:database.properties")
public class LocalDataSourceConfiguration implements DataSourceConfiguration {

	private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
	private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
	private static final String PROPERTY_NAME_DATABASE_URL = "db.url";
	private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

	private static final String PROPERTY_NAME_OPENJPA_DBDICTIONARY = "openjpa.jdbc.DBDictionary";

	@Autowired
	private Environment environment;

	@Bean
	public DataSource dataSource() {
		BasicDataSource dataSource = new BasicDataSource();
		dataSource.setDriverClassName(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
		dataSource.setUrl(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
		dataSource.setUsername(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
		dataSource.setPassword(environment.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
		return dataSource;
	}

	@Override
	public Map<String, String> contributeJpaEntityManagerProperties() throws Exception {
		Map<String, String> jpaProperties = new HashMap<String, String>();
		jpaProperties.put("PersistenceVersion", "2.0");
		jpaProperties.put(PROPERTY_NAME_OPENJPA_DBDICTIONARY,
				environment.getRequiredProperty(PROPERTY_NAME_OPENJPA_DBDICTIONARY));
		jpaProperties.put("openjpa.jdbc.MappingDefaults",
				"ForeignKeyDeleteAction=restrict, JoinForeignKeyDeleteAction=restrict");
		jpaProperties.put("openjpa.Log", "DefaultLevel=INFO, Runtime=INFO, Tool=INFO, SQL=TRACE");		
		jpaProperties.put("openjpa.jdbc.EagerFetchMode", "join");
		jpaProperties.put("openjpa.jdbc.SubclassFetchMode", "join");
		jpaProperties.put("openjpa.jdbc.SynchronizeMappings", "buildSchema(ForeignKeys=true)");
		return jpaProperties;
	}
}
